package cn.kgc.commons.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>添加描述信息</p>
 */
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    private static final String lua =
            "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1])"
                    +"else return 0 end";

    //执行lua脚本,实现分布式锁中删除锁的操作
    public boolean execute(String lockName,String uuid){
        long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(lua,Long.class),
                Arrays.asList(lockName),
                uuid
        ).longValue();
        return result==1;
    }

    public  void set(String key,Object value,long times,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value,times,timeUnit);
    }

    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

    public boolean setIfAbsent(String key,Object value,long times,TimeUnit timeUnit){
        return redisTemplate.opsForValue().setIfAbsent(key, value, times, timeUnit);
    }

    //判断hash类型中是否有元素
    public boolean hasKey(String key,Object hk){
        return redisTemplate.opsForHash().hasKey(key,hk);
    }
    //获得hash类型中的value值
    public Object get(String key,Object hk){
        return redisTemplate.opsForHash().get(key,hk);
    }
    //保存hash类型的数据
    public void putKey(String key,Object hk,Object hv){
        redisTemplate.opsForHash().put(key,hk,hv);
    }

    //根据key获得hash类型的数据
    public Map<Object,Object> getHash(String key){
        return redisTemplate.opsForHash().entries(key);
    }
    public boolean delete(String key){
        return redisTemplate.delete(key);
    }
    public boolean deleteHashKey(String key,Object hk){
        long result=redisTemplate.opsForHash().delete(key,hk);
        if(result>0){
            return true;
        }
        return false;
    }
}